package cn.tedu.demo.service.impl;

import cn.tedu.demo.ex.ServiceException;
import cn.tedu.demo.mapper.BannerMapper;
import cn.tedu.demo.pojo.dto.BannerDTO;
import cn.tedu.demo.pojo.entity.Banner;
import cn.tedu.demo.pojo.vo.BannerListVO;
import cn.tedu.demo.service.IBannerService;
import cn.tedu.demo.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class BannerServiceImplement implements IBannerService {

    @Autowired
    BannerMapper bannerMapper;
    @Override
    public String addNewBanner(MultipartFile multipartFile) {
        log.debug("进入轮播图业务层，开始处理【添加轮播图】的业务");
        String fileName= multipartFile.getOriginalFilename();
        log.debug("获取原始文件名，{}",fileName);
        String fileType=fileName.substring(fileName.lastIndexOf("."));
        log.debug("获取文件的类型，{}",fileType);
        fileName = UUID.randomUUID()+fileType;
        log.debug("获取唯一文件名，{}",fileName);
        String path=BANNER_PATH;
        log.debug("获取轮播图储存地址");
        File bannerPath=new File(path);
        if(!bannerPath.exists()){
            bannerPath.mkdirs();
        }
        String filePath=path+fileName;
        log.debug("获取完整文件名：{}",filePath);
        try {
            multipartFile.transferTo(new File(filePath));
            log.debug("向静态资源文件夹储存图片");
        } catch (IOException e) {
            String message="服务器忙，请稍后再试";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT,message);
        }
        Banner banner=new Banner();
        banner.setPicUrl(fileName);
        int rows = bannerMapper.insert(banner);
        if(rows!=1){
            String message="轮播图插入失败，服务器忙，请稍后再试";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT,message);
        }
        log.debug("轮播图保存完成");
        return fileName;
    }

    @Override
    public List<BannerListVO> getListBanner() {
        log.debug("进入轮播图业务层，开始处理【获取轮播图列表】的业务");
        List<BannerListVO> bannerList = bannerMapper.getBannerList();
        List<BannerListVO> list=new ArrayList<>();
        for (BannerListVO bannerListVO : bannerList) {
            bannerListVO.setPicUrl("project_item_imgs/"+bannerListVO.getPicUrl());
            list.add(bannerListVO);
        }
        return list;
    }
}
